# Reksio - Memory Map Editor
# Copyright (C) 2023 CERN
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
# In applying this licence, CERN does not waive the privileges and immunities
# granted to it by virtue of its status as an Intergovernmental Organization or
# submit itself to any jurisdiction.

import reksio


def validate(attr):
    attr_parent = attr.parentNode
    map_parent_name = attr_parent.name
    map_parent_ver = attr.value
    submap = attr_parent.getChildByType('memory-map')

    if submap is None:
        return True

    submap_name = submap.name
    submap_ver = submap.getAttribute(['x-map-info', 'memmap-version']).value

    warn_msg_core = f'"{map_parent_name}/x-map-info/memmap-version": map "{submap_name}" '

    if submap_ver is '' or map_parent_ver is '':
        reksio.warn(f'{warn_msg_core} is empty!')
        return False

    # Memory map version convention: e.g. "1.23.1" (major.minor.tiny)
    submap_ver_major, submap_ver_minor, submap_ver_tiny = submap_ver.split('.', 2)
    map_parent_ver_major, map_parent_ver_minor, map_parent_ver_tiny = map_parent_ver.split('.', 2)

    if submap_ver_major != map_parent_ver_major:
        reksio.warn(f'{warn_msg_core}major version "{submap_ver}" not compliant with "{map_parent_ver}"'
                             f'version (map:"{map_parent_name}")!')
        return False

    if submap_ver_minor != map_parent_ver_minor:
        reksio.warn(f'{warn_msg_core}minor version "{submap_ver}" different than map "{map_parent_ver}"'
                             f'version (map:"{map_parent_name}")!')

    return True


def getMessage():
    return "Check the x-map-info/memmap-version value."
